﻿using Serilog.Context;
using SqlSugar;


namespace MyCompany.MyProject.Common.LogHelper;

/// <summary>
/// 日志扩展类
/// </summary>
public class LogContextExtension : IDisposable
{
    private readonly Stack<IDisposable> _stack = new Stack<IDisposable>();
    public static LogContextExtension Create => new();
    //public static readonly string LogSource = "LogSource";
    //public static readonly string AopSql = "AopSql";
    //public static readonly string FileMessageTemplate = "{NewLine}Date:{Timestamp:yyyy-MM-dd HH:mm:ss.fff}{NewLine}LogLevel:{Level}{NewLine}Message:{Message}{NewLine}{Exception}" + new string('-', 100);

    /// <summary>
    /// 因为程序运行时候是多线程的，需要释放否则会内存泄露
    /// </summary>
    /// <param name="disposable"></param>
    public void AddStock(IDisposable disposable)
    {
        _stack.Push(disposable);
    }

    public IDisposable SqlAopPushProperty(ISqlSugarClient db)
    {
        AddStock(LogContext.PushProperty(LogContextStatic. LogSource, LogContextStatic.AopSql));
        AddStock(LogContext.PushProperty(LogContextStatic.SqlOutToConsole,
            AppSettings.app(new string[] { "AppSettings", "SqlAOP", "LogToConsole", "Enabled" }).ObjToBool()));
        AddStock(LogContext.PushProperty(LogContextStatic.SqlOutToFile,
            AppSettings.app(new string[] { "AppSettings", "SqlAOP", "LogToFile", "Enabled" }).ObjToBool()));
        AddStock(LogContext.PushProperty(LogContextStatic.OutToDb,
            AppSettings.app(new string[] { "AppSettings", "SqlAOP", "LogToDB", "Enabled" }).ObjToBool()));

        AddStock(LogContext.PushProperty(LogContextStatic.SugarActionType, db.SugarActionType));

        return this;
    }
    public void Dispose()
    {
        while (_stack.Count > 0)
        {
            _stack.Pop().Dispose();
        }
    }
}
